package cn.itsource.pet.controller;

import cn.itsource.basic.utils.*;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.service.IShopService;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import cn.itsource.user.domain.User;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

//searchMasterMsg/publish
@RestController
@RequestMapping("/searchMasterMsg")
public class SearchMasterMsgController {
    @Autowired
    private ISearchMasterMsgService seachMasterMsgService;

    @Autowired
    private IShopService shopService;


    @PostMapping("/publish")
    public AjaxResult publish(@RequestBody  SearchMasterMsg searchMasterMsg, HttpServletRequest request){
        //1 searchMasterMsg 没有发布用户， 没有店铺
        // 获取当前的系统登录用户
        // redis     key                  value
        //       fdahisfhasaspoasdas      {"name":""，"age":10 } 用户对象的json字符串
        String redisKey = request.getHeader("U-TOKEN");
        //{"createtime":1608174171000,"id":41,"password":"06ecd850214d6e705a06ca70a2a44350","phone":"15008495702","salt":"2417654e-813e-4030-9213-4ebf79335f57","state":1}
        String userJson = RedisUtils.INSTANCE.get(redisKey);
        // 把json转换为对象
        User user = JSONObject.parseObject(userJson, User.class);
        //设置发布消息的用户信息
        searchMasterMsg.setUser(user);
        //2.获取离用户最近的 门店

        //用户发布地址的经纬度
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        List<Shop> shopList = shopService.query();
        //计算出最近的商家
        Shop shop = DistanceUtil.getNearestShop(point, shopList);
        searchMasterMsg.setShop(shop);
        //设置消息状态为待处理
        searchMasterMsg.setState(0);
        seachMasterMsgService.save(searchMasterMsg);
        //给商家发送一条短信


        return AjaxResult.me();
    }

    //店铺没有处理的消息
    @PostMapping("/processed")
    public PageResult<SearchMasterMsg> loadList(SearchMasterMsgQuery query){
        //1.获取当前登录的店铺信息
            //获取店铺登录的id
        //2.
        query.setShopId(38L);
        PageResult<SearchMasterMsg> result = seachMasterMsgService.queryPage(query);


        return  result;
    }
}
